<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>增加入库单</title>
    <link rel="stylesheet" href="../css/from.css">
    <link rel="stylesheet" href="../themes/default/easyui.css">
    <link rel="stylesheet" href="../themes/icon.css">
    <script src="../js/jquery.min.js"></script>
    <script src="../js/jquery.easyui.min.js"></script>
    <script src="../js/easyui-lang-zh_CN.js"></script>
    <script>
    //打印之后在打印
    function print(){
        if($("#saveInstroageBill").attr("disabled")!='disabled'){
                alert("请点击保存后在打印");
                return false;
            }
    }
    //审核
        function checkStatus(){
           var codes=[];
            var row=$("#addInstroage").datagrid('getData');
            //var row=$('#addInstroage').datagrid('getRows');
             for(var i=0;i<row.rows.length;i++){
                var bill={}
                bill.code=row.rows[i].code;
                bill.amount=row.rows[i].amount==null?1:row.rows[i].amount;
                bill.price=row.rows[i].price==null?1:row.rows[i].price;
                bill.memo=row.rows[i].memo==null?"":row.rows[i].memo;
                bill.orderCode=row.rows[i].billCode==null?"":row.rows[i].billCode;
                codes[i]=bill
            } 
            var detail=JSON.stringify(codes);
            var detail2=JSON.stringify(serializeJson());
             $.post("/kxmanage/instroageBill/saveInstroageBill.json?total="+compute(),{"codes":detail,"inBill":detail2},addInstroageBillResult,"json");
        }
        function addInstroageBillResult(data){
            if(data.result=="success"){
                $.post("/kxmanage/instroageBill/checkStatusInstroageBill.json",{"billCode":$("#code").val()},resultCheckStatus,"json");
            }else if(data.result=="noPower"){
        				alert("您没有权限！");
        			}else{
                alert("审核失败!");
            }
        }
        function resultCheckStatus(data){
            if(data.result=="success"){
               alert("审核成功!");
               var code=$("#code").val();
               self.parent.$("#jxc_tabs").tabs("close","增加入库单");
               parent.addTabs("修改入库单","../instroageBill/modifyInstroageBill.html?code="+code);
               //self.parent.$("#jxc_tabs").tabs("close","修改入库单");
           }else if(data.result=="noPower"){
        				alert("您没有权限！");
        			}else{
               alert("审核失败!");
           }
        }
    //刷新增加入库单
         function addtabs(){
             self.parent.addTabs("增加入库单","goods/addInstroageBill.jsp");
            }
        //可编辑单元格
         $.extend($.fn.datagrid.methods, {
			editCell: function(jq,param){
				return jq.each(function(){
					var opts = $(this).datagrid('options');
					var fields = $(this).datagrid('getColumnFields',true).concat($(this).datagrid('getColumnFields'));
					for(var i=0; i<fields.length; i++){
						var col = $(this).datagrid('getColumnOption', fields[i]);
						col.editor1 = col.editor;
						if (fields[i] != param.field){
							col.editor = null;
						}
					}
					$(this).datagrid('beginEdit', param.index);
					//获取编辑行
					var editors = $("#addInstroage").datagrid('getEditors', param.index);
						var sfgzEditor = editors[0];
						//绑定失焦事件并取消可编辑状态
						 if(sfgzEditor!=undefined){
						    sfgzEditor.target.bind('blur', function () {
						     $("#addInstroage").datagrid('endEdit', param.index);
						    editIndex = undefined;
					//update();
					     });
						}
					for(var i=0; i<fields.length; i++){
						var col = $(this).datagrid('getColumnOption', fields[i]);
						col.editor = col.editor1;
					}
				});
			}
		}); 
		 $.extend($.fn.datagrid.defaults.editors, {    
		    numberbox: {    
		        init: function(container, options){    
		            var input = $('<input type="number" class="datagrid-editable-input">').appendTo(container);    
		            return input;    
		        },    
		        getValue: function(target){    
		            return $(target).val();    
		        },    
		        setValue: function(target, value){    
		            $(target).val(value);    
		        },    
		        resize: function(target, width){    
		            var input = $(target);    
		            if ($.boxModel == true){    
		                input.width(width - (input.outerWidth() - input.width()));    
		            } else {    
		                input.width(width);    
		            }    
		        }    
		    } 
		});
		$.extend($.fn.datagrid.defaults.editors, {    
		    text: {    
		        init: function(container, options){    
		            var input = $('<input type="text" class="datagrid-editable-input">').appendTo(container);    
		            return input;    
		        },    
		        getValue: function(target){    
		            return $(target).val();    
		        },    
		        setValue: function(target, value){    
		            $(target).val(value);    
		        },    
		        resize: function(target, width){    
		            var input = $(target);    
		            if ($.boxModel == true){    
		                input.width(width - (input.outerWidth() - input.width()));    
		            } else {    
		                input.width(width);    
		            }    
		        }    
		    }    
		});
		var editIndex = undefined;
		function endEditing(){
			if (editIndex == undefined){return true}
			if ($("#addInstroage").datagrid('validateRow', editIndex)){
				$("#addInstroage").datagrid('endEdit', editIndex);
				editIndex = undefined;
				return true;
			} else {
				return false;
			}
		}
		function onClickCell(index, field){
			if (endEditing()){
				$("#addInstroage").datagrid('selectRow', index)
						.datagrid('editCell', {index:index,field:field});
				editIndex = index;
			}
		}
		//删除
		function deleteRightGridRow(rowId){  
		    $("#addInstroage").datagrid('deleteRow', rowId);
		    var rows = $("#addInstroage").datagrid('getFooterRows');
			rows[0]['amount'] = computeFlied("amount");
			rows[0]['money'] = compute("money");
			$("#addInstroage").datagrid('reloadFooter');	
         }
         //求各个字段的和
        function computeFlied(colName) {
			var rows = $("#addInstroage").datagrid('getRows');
			var total = 0;
			for (var i = 0; i < rows.length; i++) {
				total += parseFloat(rows[i][colName]);
			}
			return total;
		}
         //指定列求和
        function compute(colName) {
			var rows = $("#addInstroage").datagrid('getRows');
			var total = 0;
			for (var i = 0; i < rows.length; i++) {
				total += parseFloat((rows[i]["price"]==undefined?0:rows[i]["price"])*(rows[i]["amount"]==undefined?1:rows[i]["amount"]));
			}
			return total;
		}
        //保存入库单
        function saveInstroageBill(){
            var codes=[];
            var row=$("#addInstroage").datagrid('getData');
            //var row=$('#addInstroage').datagrid('getRows');
             for(var i=0;i<row.rows.length;i++){
                var bill={}
                bill.code=row.rows[i].code;
                bill.amount=row.rows[i].amount==null?1:row.rows[i].amount;
                bill.price=row.rows[i].price==null?1:row.rows[i].price;
                bill.memo=row.rows[i].memo==null?"":row.rows[i].memo;
                bill.orderCode=row.rows[i].billCode==null?"":row.rows[i].billCode;
                codes[i]=bill
            } 
            var detail=JSON.stringify(codes);
            var detail2=JSON.stringify(serializeJson());
            $.post("/kxmanage/instroageBill/saveInstroageBill.json?total="+compute(),{"codes":detail,"inBill":detail2},saveInstroageBillResult,"json");
        }
        //ajax成功
        function saveInstroageBillResult(data){
           if(data.result=="success"){
               alert("保存成功！")
               self.parent.addTabs("入库单管理","goods/instroageBillList.jsp");
               self.parent.$("#jxc_tabs").tabs("close","增加入库单");
           }else if(data.result=="noPower"){
        	  alert("您没有权限！");
           }else{
               alert("保存失败！");
           }
        }
        //表单序列化
        function serializeJson(){  
            var serializeObj={};  
            var array=$("#form").serializeArray();  
            var str=$("#form").serialize();  
            $(array).each(function(){  
                if(serializeObj[this.name]){  
                    if($.isArray(serializeObj[this.name])){  
                        serializeObj[this.name].push(this.value);  
                    }else{  
                        serializeObj[this.name]=[serializeObj[this.name],this.value];
                    }  
                }else{  
                    serializeObj[this.name]=this.value;   
                }  
            });  
                return serializeObj;  
            }; 
        //配件列表
        function loadPart(){
            var companyName=$("#customName").val();
            if(companyName==null||companyName==''){
                alert("供应商名称不能为空！");
                return false;
            }
            var content="<iframe src='showPartList.jsp' frameborder='0'style='width: 100%;height: 100%'></iframe>";
            $("#list").dialog({
                content: content,
                title: '配件列表',
                width: 950,
                height: 340,
                closed: false,
                cache: false,
                modal: true,
            });
        }
        //供应商列表
        function loadSupplier() {
            var content="<iframe src='showBillList.jsp' frameborder='0'style='width: 100%;height: 100%'></iframe>";
            $("#list").dialog({
                content: content,
                title: '供应商列表',
                width: 900,
                height: 340,
                closed: false,
                cache: false,
                modal: true,
            });
        }
        //采购订单
        function loadSupplierOrder() {
            var companyName=$("#customName").val();
            if(companyName==null||companyName==''){
                alert("供应商名称不能为空！");
                return false;
            }
            var content="<iframe src='showSupplierOrder.jsp' frameborder='0'style='width: 100%;height: 100%'></iframe>";
            $("#list").dialog({
                content: content,
                title: '采购订单',
                width: 900,
                height: 340,
                closed: false,
                cache: false,
                modal: true,
            });
        }
        function closeDg(name) {
            $("#supplierName").val(name);
            $("#list").dialog("close");
        }
        function closetabs(){
            self.parent.$("#jxc_tabs").tabs("close","增加入库单");
        }
        $(function(){
			$("#instroageDate").datetimebox("setValue",nowtime());
            var editIndex = undefined;
           //增加配件表格
            $("#addInstroage").datagrid({
                fitColumns:true,
                url:'/kxmanage/instroageBill/getPartByCode.json',
                rownumbers:true,
                checkOnSelect:false,
                columns:[[
                    {field:'billCode',title:'订单编号',width:140},
                    {field:'partNo',title:'件号',width:80},
                    {field:'partName',title:'配件名称',width:180},
                    {field:'partBrand',title:'配件品牌',width:60,
                        formatter:function (value,row,index) {
                            if(row.isFooter){
                                return row.partBrand;
                            }
                            return row.partBrand;
                        }},
                    {field:'typeName',title:'配件型号',width:100},
                    {field:'amount',title:'数量',width:100,editor:'numberbox',
                        formatter:function (value,row,index) {
                            if(row.isFooter){
                                return row.amount;
                            }
                            if(row.amount==undefined){
                                return 1;
                            }
                            return row.amount;
                        }},
                    {field:'price',title:'单价(￥)',editor:'numberbox',
                        formatter:function (value,row,index) {
                            if(row.isFooter){
                                return "";
                            }
                            if(row.price==undefined){
                                return "0.00";
                            }
                            return row.price+"￥";
                        }},
                    {field:'money',title:'金额(￥)',width:100,
                        formatter:function (value,row,index) {
                        
                            if(row.isFooter){
                                return row.money+"￥";
                            }
                            if(row.amount==undefined){
                                return "0.00￥";
                            }
                            return row.amount*row.price+"￥";
                        }},
                    {field:'memo',title:'备注',width:100,editor:'text'},
                    {field:'oldPrice',title:'上次单价',width:100},
                    {field:'action',title:'操作',width:100,
                        formatter:function (value,row,index) {
                            if(row.isFooter){
                                return "";
                            }
                            var context="<a href=\"javascript:deleteRightGridRow('"+index+"')\">删除</a>&nbsp;&nbsp;";
                            return context;
                        }}
                ]],
                toolbar:'#wu_toolbar',
                showFooter:true,
                onClickCell:onClickCell,
                onAfterEdit:function(index, row, changes){
	                var rows = $("#addInstroage").datagrid('getFooterRows');
					rows[0]['amount'] = computeFlied("amount");
					rows[0]['money'] = compute("money");
					$("#addInstroage").datagrid('reloadFooter');
                },
                 rowStyler: function (index, row) {
	                var rows = $("#addInstroage").datagrid("selectRow"); 
	                if (rows) {
	                    return 'background-color:#ffffff;';
	                } else {
	                    return 'background-color:#ffffff;';
	                }
	            }
                /* function(index, field, value){
					if (editIndex == undefined) { 	
					    //if(field=="price"){ // 判断是否是field为six列，如果不是固定某列的话，不需要判断 	 	
						$(this).datagrid('beginEdit', index);           	
						var ed = $(this).datagrid('getEditor', {index:index,field:field});                  
						$(ed.target).focus(); 
					   // }              	 
					    editIndex = index;     	 
					   // alert("点击触发editIndex:"+editIndex);  	
					}else if(editIndex != undefined){//如果不相等，说明已经打开编辑器了，需要关闭编辑器		
						$(this).datagrid('endEdit', editIndex);  		
						editIndex = undefined;		
						//alert("关闭编辑器");	
					}	
					//$("#addInstroage").datagrid('onClickRow')
					
				}  */
            })
           //添加入库类型下拉框
           $.post("/kxmanage/instroageBill/getInstroageType",{"type":"入库类型"},appendInstroageType);
           function appendInstroageType(data){
               for(var i=0;i<data.length;i++){
                   var str="<option value='"+data[i].value+"'>"+data[i].key+"</option>";
                   $("#instroageType").append(str);
               }
           }
           //添加当前时间
            $("#instroageDate").val(nowtime());
            //添加编号
            $.post("/kxmanage/instroageBill/createInstroageBillCode",{"firstCode":"RK"},createCode);
            function createCode(data){
                $("#code").val(data)
            }
            //当前时间
            function nowtime(){
	           var time=new Date();
	           var hour=time.getHours();
	           var mini=time.getMinutes();
	           var sec=time.getSeconds();
	           var dd=time.getDate();
	           var mm=time.getMonth()+1;
	           var yy=time.getUTCFullYear();
	           var timearr ;
	            timearr= new Array(hour,mini,sec);
	             for (i = 0; i < 3; i++)
	             {
	                
	        		 if(timearr[i]<10)
	        		    timearr[i]="0"+timearr[i].toString();
	                  
	             }
	           var timestr=yy+"-"+mm+"-"+dd+" "+timearr[0]+":"+timearr[1]+":"+timearr[2];
	           return timestr;
        } 
        });
    </script>
    <style>
        body {
            font-size:12px;
            padding:10px
        }
        .l-table-edit {
     	   border-collapse:collapse;border-spacing:0;
        }
        .l-table-edit-td {
            padding:4px;
            font-size:12px;
            border: #84a0c4 1px solid;
        }
        
        input[type='text']{
        	height:20px !important;
        }
        
    </style>


</head>
<body>

<form name="form"  id="form" action="" method="post">
    <table cellpadding="0" cellspacing="0" border="1" class="l-table-edit" style="width:100%;margin:10px 0;"  >
        <tr >
            <td width="17%"  align="right" class="l-table-edit-td">产品编号：</td>
            <td width="27%" align="left" class="l-table-edit-td"><input  type="text" id="code" name="code" value="XJ20180731204051" size="30" maxlength="100" readonly="readonly" ltype="text" /></td>
            <td width="13%"  align="right" class="l-table-edit-td">添加日期：</td>
            <td width="43%" align="left" class="l-table-edit-td"><input  type="text" id="instroageDate" name="instroageDate"  value="" class="easyui-datetimebox" maxlength="30" /></td>
        </tr>
        <tr>
            <td width="17%" align="right" class="l-table-edit-td">
                <a href="javascript:loadSupplier()">供应商：</a>
            </td>
            <td align="left" class="l-table-edit-td">
                <input type="text" id="customName" name="customName"  readonly="readonly" value="" size="30" maxlength="100" ltype="text"  />
            <td width="13%" align="right" class="l-table-edit-td">联系人：</td>
            <td align="left" class="l-table-edit-td">
                <input name="linkman" type="text" id="linkman" value="" maxlength="30" ltype="text" /></td>
        </tr>
        <tr>
            <td width="17%" align="right" class="l-table-edit-td">电话：</td>
            <td align="left" class="l-table-edit-td"><input  type="text" id="phone" name="phone" value="" size="30" maxlength="50" ltype="text" /></td>
            <td width="17%" align="right" class="l-table-edit-td">入库类型：</td>
            <td align="left" class="l-table-edit-td"><select id="instroageType" name="instroageType"></select></td>
        </tr>
        <tr>
            <td align="right" class="l-table-edit-td" valign="top">备注：</td>
            <td align="left" class="l-table-edit-td" colspan="3">
                <textarea  rows="1" name="memo" id="memo" class="l-table-edit" style="width:90%" ></textarea>
            </td>
        </tr>
    </table>
</form>
<br>
<div style="margin-bottom:20px;">
    <input  type="button" onclick="addtabs()" value="新   增" style="width:60px">
	<input  type="button" onclick="loadSupplierOrder()" value="采购订单" style="width:60px">
	<input  type="button" onclick="loadPart()" value="添加配件" style="width:60px">
	<input  type="button" onclick="saveInstroageBill()" value="保存" style="width:60px">
	<input  type="button" value="审核" onclick="checkStatus()" style="width:60px">
	<input  type="button" value="撤销" style="width:60px">
	<input  type="button" value="生成采购付款" style="width:100px">
	<input  type="button" value="生成采购收票" style="width:100px">
	<input  type="button" onclick="print()" value="打印" style="width:60px">
	<input  type="button" onclick="closetabs()" value="关闭" style="width:60px">
</div>
<div id="list"  style="display: none;"></div>
<!-- <div data-options="fit:true"> -->
    <div id="addInstroage"  class="easyui-datagrid">

    </div>
<!-- </div> -->
</body>
</html>